<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
    <script src="static/js/axios.min.js"></script>
    <script src="https://kit.fontawesome.com/bb97f7b388.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="static/css/style.css">
    <link rel="stylesheet" href="static/css/my.css">
    <link rel="stylesheet" href="static/css/sidebar.css">
    <script src="static/js/app.js"></script>
    <title>花瓣 | 评分</title>
</head>

<body>
    <div class="blocks" id="app">
        <div class="nav" id="nav">
            <nav class="nav_content">
                <a href="#" class="nav_logo">
                    <i class='bx'>
                        <img src="static/img/Icon.png" alt="" style="width: 45px;height: 40px;">
                    </i>
                    <span class="nav_logo-name">花瓣</span>
                </a>
                <div class="nav_list">
                    <a href="/vscf/index.html" class="nav_link ">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">首页</span>
                    </a>
                    <a class="nav_link" href="/vscf/category.html">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">分类</span>
                    </a>
                    <a class="nav_link active-link" href="#">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">我的</span>
                    </a>
                    <div class="sidebar-line"></div>

                    <a class="nav_link" href="/vscf/us.html">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">关于我们</span>
                    </a>
                    <a href="javascript:void(0);" class="nav_link" @click="logout();">
                        <i class='bx bxs-log-in'></i>
                        <span class="nav_name">登出</span>
                    </a>
                </div>
            </nav>
            <footer class="footer"
                style="display:flex;flex-direction: column;justify-content: center;align-items: baseline;width: 203px;">
                <div class="footer-line">Powered By Cross Fire • © 2024</div>
            </footer>
        </div>
        <section class="middle">
            <div class="header" style="justify-content: flex-end;">
                <div class="profile-count">
                    <i class='bx bxs-plus-circle'></i>
                    <i class='bx bxs-bell'></i>
                    <a href="/vscf/my.html">
                        <img class="profile-photo" :src="imgurl || 'static/img/Icon.png'" alt="Profile Photo">
                    </a>
                </div>
            </div>

            <div class="modal">
                <img src="img/profile.jpg" alt="">
                <div class="close"></div>
            </div>

            <div class="container" style="margin-left: 0px!important;">
                <div class="card">
                    <div class="header_1">
                        <div class="hamburger-menu">
                            <div class="center"></div>
                        </div>
                        <a href="#" class="mail">
                            <i class="far fa-envelope"></i>
                        </a>
                        <div class="main">
                            <form id="uploadForm" method="post" enctype="multipart/form-data">
                                <div class="image" @click="triggerFileInput">
                                    <img :src="imgurl || 'default-avatar.png'" alt="User avatar"
                                        style="width: 100px;height: 100px;">
                                    <input type="file" name="image" id="image" ref="fileInput" style="display: none;"
                                        @change="onFileChange">
                                </div>
                            </form>
                            <h3 class="name">{{ user ? user.name : '加载中...' }}</h3>
                            <h3 class="sub-name">{{ user ? user.account : '' }}</h3>
                        </div>
                    </div>
                    <div class="content" style="justify-content: space-between;">
                            <div class="left">
                                <div class="about-container">
                                    <h3 class="title">About</h3>
                                    <p class="text" style="margin-bottom: 10px;font-size:18px;">年龄：{{ user ? user.age :
                                        '' }}</p>
                                    <p class="text" style="margin-bottom: 10px;font-size:18px;">邮箱：{{ user ? user.email
                                        : '' }}</p>
                                    <p class="text" style="margin-bottom: 10px;font-size:18px;">性别：{{ user ? user.sexy :
                                        '' }}</p>
                                    <p class="text" style="margin-bottom: 10px;font-size:18px;">账户状态：{{ user ?
                                        user.state : '' }}</p>
                                </div>

                                <div class="buttons-wrap">
                                    <div class="share-wrap" @click="openEditForm">
                                        <a href="#" class="share">修改信息</a>
                                    </div>
                                    <!-- 上传按钮仅在选择文件后显示 -->
                                    <!--<button type="submit" v-if="isFileSelected" @click="handleUpload">上传</button>-->
                                    
                                    
                                    <div class="share-wrap" type="submit" v-if="isFileSelected" @click="handleUpload">
                                        <a href="#" class="share">上传头像</a>
                                    </div>
                                    
                                    
                                    
                                </div>
                                 <div v-if="isUploading" class="uploading-status">
                <p>上传中，请稍等...</p>
                <div class="loading-spinner"></div> <!-- 可以加一个旋转的加载图标 -->
            </div>
                            </div>

                            <div class="right">
                                <div>
                                    <h3 class="number">{{ user ? user.commentall : '' }}</h3>
                                    <h3 class="number-title">评论数</h3>
                                </div>
                            </div>
                    </div>
                     
                </div>
            </div>

                <div class="cf-topics" style="position: relative;top: -120px;">
                    <div class="cf-title">
                        <i class='bx bxs-conversation'></i>
                        <p class="cf-title-text" style="font-size: 20px;">我的关注</p>
                    </div>
                    <div v-if="topworks.length > 0">
                        <div v-for="topic in topworks" :key="topic.id" class="cf-topics-count"
                            style="display: grid; grid-template-columns: 0.8fr 0.2fr;" @click="goToDetails(topic.id)">
                            <div class="cf-topics-texts">
                                <div class="cf-topics-icon-1"
                                    style="display: flex;justify-content: center;align-items: center;">
                                    <img :src="topic.img" alt="" style="width: 180px;height: 80px;border-radius: 5px;">
                                </div>
                                <div class="cft-text">
                                    <p class="cf-topic-name">{{ topic.title }}</p>
                                    <p class="forum-type">{{ topic.introduction }}</p>
                                </div>
                            </div>
                            <div style="display: flex;flex-direction: column;justify-content: space-between;">
                                <div class="cf-topic-reactions">
                                    <div class="cf-topic-threads">
                                        <p style="font-size: 15px;">浏览量</p>
                                        <p class="threads-amount">{{ topic.viewcount || 'N/A' }}</p>
                                    </div>
                                    <div class="cf-topic-messages">
                                        <p style="font-size: 15px;">团队</p>
                                        <p class="messages-amount">{{ topic.producer || 'N/A' }}</p>
                                    </div>
                                </div>
                                <div style="display: flex;flex-direction: column;">
                                    <p style="display: flex; justify-content: flex-end;">发布日期</p>
                                    <p style="display:flex;justify-content: flex-end;">{{ topic.date }}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div v-else>
                        <p>还没有关注哦！.</p>
                    </div>
                </div>

                <!-- 修改个人信息表单 -->
                <div id="edit-form" class="edit-form" v-show="isEditFormVisible">
                    <div class="form-container">
                        <h3>Edit Profile</h3>
                        <div class="close-form" @click="closeEditForm">X</div>
                        <form @submit.prevent="submitForm">
                            <!-- 昵称 -->
                            <div class="form-group">
                                <label for="name">昵称</label>
                                <input v-model="formData.name" type="text" id="name" name="name">
                            </div>
                            <!-- 电子邮件 -->
                            <!--<div class="form-group">-->
                            <!--    <label for="email">电子邮件</label>-->
                            <!--    <input v-model="formData.email" type="email" id="email" name="email">-->
                            <!--</div>-->
                            <!-- 年龄 -->
                            <div class="form-group">
                                <label for="age">年龄</label>
                                <input v-model="formData.age" type="number" id="age" name="age">
                            </div>
                            <!-- 性别 -->
                            <div class="form-group">
                                <label for="sexy">性别</label>
                                <select v-model="formData.sexy" id="sexy" name="sexy">
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </div>
                            <!-- 密码 -->
                            <div class="form-group">
                                <label for="password">密码</label>
                                <input v-model="formData.password" type="password" id="password" name="password">
                            </div>
                            <button type="submit" class="submit-btn">提交修改</button>
                        </form>
                    </div>
                </div>
            </div>
        </section>
    </div>

        <script>
            new Vue({
                el: '#app',
                data() {
                    return {
                        user: [],
                        userid: null,
                        topworks: [],
                        formData: {
                            name: '',
                            email: '',
                            age: '',
                            sexy: '男',
                            password: ''
                        },
                        isEditFormVisible: false,
                        imgurl: null,
                        isFileSelected: false,
                          isUploading: false, 
                    }
                },
                created() {
                    this.checkUserSession();
                },
                methods: {
                    getUserSession() {
                        axios.get('/vscf/user/getSessionUser')
                            .then(response => {
                                if (response.data.success) {
                                    this.user = response.data.user;
                                    this.imgurl = response.data.user.avatar;
                                    this.userid = response.data.user.id;
                                    this.initWorks();
                                } else {
                                    console.log("No user session found.");
                                }
                            })
                            .catch(error => {
                                console.error('Error fetching user session:', error);
                            });
                    },
                    openEditForm() {
                        this.isEditFormVisible = true;
                    },
                    closeEditForm() {
                        this.isEditFormVisible = false;
                    },
                    async initWorks() {
                        const url = `/vscf/works/findattentionworks?userid=${this.userid}`;
                        try {
                            const response = await axios.get(url);

                            // 检查返回数据类型，并解析正确的数据结构
                            if (typeof response.data === 'string') {
                                this.topworks = JSON.parse(response.data).worksList;  // 如果是字符串，先解析为 JSON
                            } else {
                                this.topworks = response.data.worksList;  // 直接获取 worksList 数据
                            }

                            // 对图片路径进行处理，确保每个作品的图片路径是第一个路径
                            this.topworks = this.topworks.map(item => {
                                let img = item.img;
                                let primaryImage = '';

                                if (img) {
                                    if (img.includes(',')) {
                                        primaryImage = img.split(',')[0].trim();  // 如果是逗号分隔，取第一个路径
                                    } else {
                                        primaryImage = img;  // 如果是单个图片路径，直接使用
                                    }
                                } else {
                                    primaryImage = '';  // 如果没有图片路径，设置为空
                                }

                                return {
                                    ...item,  // 保留原始数据
                                    img: primaryImage,  // 替换为处理后的图片路径
                                };
                            });
                        } catch (error) {
                            console.error('请求数据失败:', error);
                        }
                    },
                    async submitForm() {
                        const updatedData = {
                            name: this.formData.name || this.user.name,        // 姓名字段
                            // email: this.formData.email || this.user.email,     // 邮箱字段
                            age: this.formData.age || this.user.age,          // 年龄字段
                            sexy: this.formData.sexy || this.user.sexy,       // 性别字段
                            password: this.formData.password || this.user.password,  // 密码字段
                        };

                        try {
                            const response = await axios.post('/vscf/user/updateProfile', updatedData);
                            if (response.data.success) {
                                alert('个人信息更新成功');
                                window.location.href = '/my.html';  // 更新成功后跳转到个人页面
                            } else {
                                alert('更新失败: ' + response.data.message);
                            }
                        } catch (error) {
                            console.error('Error:', error);
                            // 如果是网络或服务器错误，提示用户重试
                            if (error.response) {
                                // HTTP 错误响应
                                alert(`请求失败，错误码：${error.response.status}，请稍后再试。`);
                            } else if (error.request) {
                                // 请求已发出，但没有响应
                                alert('请求未得到响应，可能是网络问题，请检查网络连接或稍后重试。');
                            } else {
                                // 其他错误
                                alert('发生未知错误，请重试。');
                            }
                        }
                    }
                    ,

                    logout() {
                        axios.post('/vscf/user/logout')
                            .then(response => {
                                localStorage.removeItem('userToken');
                                sessionStorage.removeItem('userToken');
                                window.location.href = '/';
                            })
                            .catch(error => {
                                console.error('登出失败:', error);
                            });
                    },
                    checkUserSession() {
                        axios.get('/vscf/user/getSessionUser')
                            .then(response => {
                                if (response.data.success && response.data.user) {
                                    this.getUserSession();
                                } else {
                                    window.location.href = '/vscf/login.html';
                                }
                            })
                            .catch(error => {
                                console.error('Error fetching user session:', error);
                                window.location.href = '/vscf/login.html';
                            });
                    },
                    goToDetails(topicId) {
                        window.location.href = `/vscf/particulars.html?id=${topicId}`;
                    },
                    triggerFileInput() {
                        this.$refs.fileInput.click(); // 触发文件选择框
                    },
                    onFileChange(event) {
                        const file = event.target.files[0]; // 获取选择的文件
                        if (file) {
                            this.isFileSelected = true;  // 设置状态为文件已选择
                            this.imgurl = URL.createObjectURL(file);  // 使用本地文件生成预览URL
                        } else {
                            this.isFileSelected = false; // 如果未选择文件，隐藏上传按钮
                        }
                    },
                     handleUpload() {
            const formData = new FormData();
            const fileInput = this.$refs.fileInput;

            // 判断是否选择了文件
            if (fileInput.files.length === 0) {
                alert('请先选择一个文件');
                return;
            }

            // 设置上传状态为正在上传
            this.isUploading = true;

            // 将文件添加到 FormData 中
            formData.append('image', fileInput.files[0]);
            formData.append('userid', this.user.id);  // 可以将用户 ID 添加到表单数据中

            // 使用 axios 发送 POST 请求上传文件
            axios
                .post('/vscf/uploadImage', formData)
                .then((response) => {
                    this.isUploading = false;  // 上传完成，设置状态为结束
                    if (response.data.success) {
                        this.imgurl = response.data.imageUrl;  // 更新头像URL
                        alert('头像上传成功');
                    } else {
                        alert(response.data.message);
                    }
                })
                .catch((error) => {
                    this.isUploading = false;  // 上传失败，设置状态为结束
                    alert('上传失败，请稍后再试');
                });
        },
                }
            });
        </script>
</body>

</html>